﻿package rd.hardcore.engine.save 
{
	import flash.desktop.NativeApplication;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.InvokeEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.system.Capabilities;
	import flash.utils.getTimer;
	import flash.utils.setTimeout;
	import fr.digitas.flowearth.conf.Conf;
	import rd.debug.Debug;
	import rd.hardcore.engine.datas.DatasManager;
	import rd.hardcore.ui.pad.PadsManager;
	
	/**
	 * Initialise les confs utilisateur
	 * Garant du passage agréable d'une update à l'autre
	 * @author Thibault Perret
	 */
	public class InitUserConf extends EventDispatcher
	{
		
		private var tracksFile:File = File.applicationStorageDirectory.resolvePath("tracks.xml");
		private var padsFile:File = File.applicationStorageDirectory.resolvePath("pads.xml");
		private var tracksXML :XML;
		private var padsXML:XML;
		private var a_keyCode:Array = [65, 90, 69, 82, 84, 89, 85, 73, 79, 80, 81, 83, 68, 70, 71, 72, 74, 75, 76, 77, 87, 88, 67, 86, 66, 78];
		
		private var xmlPadLevel:Vector.<XML>;
		private var t1:int;
		
		public function InitUserConf() 
		{
		}
		
		public function start():void
		{
			
			CONFIG::debug {
				t1 = getTimer();
			}
			
			var fs:FileStream = new FileStream;
			
			/*			TRACKS.XML			*/
			
			if (!tracksFile.exists) {
				/*	1st utilisation, création du fichier de sauvegarde utilisateurs		*/
				var xmlData:XML = <data></data>;
				xmlData.appendChild( Conf.getDatas("tracks") );
				var tracksXMLStr:String = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + xmlData.toXMLString();
				fs.open(tracksFile, FileMode.WRITE);
				
				try {
					fs.writeUTFBytes(tracksXMLStr);
				}catch (e:Error) {
					trace(e.errorID + " :: " + e.message);
				}
				
				fs.close();
				tracksXML  = new XML(tracksXMLStr).tracks[0];
			}else {
				fs.open(tracksFile, FileMode.READ);
				var tracksXmlString:String = fs.readUTFBytes(fs.bytesAvailable);
				var tracksXMLList:XMLList = new XMLList(tracksXmlString);
				tracksXML = tracksXMLList.tracks[0];
				
				fs.close();
			}
			/*			PADS.XML			*/
			
			if (!padsFile.exists) {
				/*	1st utilisation, création du fichier de sauvegarde utilisateurs		*/
				var xmlDataPads:XML = <data></data>;
				xmlDataPads.appendChild( Conf.getDatas("pads") );
				var padsXMLStr:String = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + xmlDataPads.toXMLString();
				fs.open(padsFile, FileMode.WRITE);
				
				try {
					fs.writeUTFBytes(padsXMLStr);
				}catch (e:Error) {
					trace(e.errorID + " :: " + e.message);
				}
				
				fs.close();
				padsXML  = new XML(padsXMLStr).pads[0];
			}else {
				
				fs.open(padsFile, FileMode.READ);
				var padsXmlString:String = fs.readUTFBytes(fs.bytesAvailable);
				var padsXMLList:XMLList = new XMLList(padsXmlString);
				padsXML = padsXMLList.pads[0];
				
				fs.close(); 
				
			}
			
			/**
			 * I N I T   D A T A S
			 */
			var datasManager:DatasManager = new DatasManager();
			datasManager.init(tracksXML, padsXML);
			
			CONFIG::debug {
				trace("0:- inituserConf ->" + (getTimer() - t1)+"ms");
			}
			
			NativeApplication.nativeApplication.addEventListener(InvokeEvent.INVOKE, _onInvoke);
		
			setTimeout(launchRest, 2500);
		}
		
		private function _onInvoke(e:InvokeEvent):void 
		{
			Debug.log("--==--> " + e.currentTarget );
			var items:Array = e.arguments;
                for( var i:int = 0; i < items.length; i++ )
                {
                    Debug.log( items[i] );
					DatasManager.addPadDefault( items[i] );
                }
		}
		
		private function launchRest():void
		{
			urlCheckerManager();
			dispatchEvent(new Event(Event.COMPLETE));
		}
		
		// maintains old versions ...
		private function urlCheckerManager() : void
		{
			CONFIG::debug {
				t1 = getTimer();
			}
			
			var _mp3Destination : File; 
			var _picDestination : File;
			
			var _mp3Empty : File = new File( SaveManager.OLD_URL_PATH_MP3 +"/empty.mp3"); 
			var _picEmpty : File = new File( SaveManager.OLD_URL_PATH_THUMB +"/empty.jpg");
			
			if ( Capabilities.os.search("Mac") < 0 ) 
				_mp3Destination = File.applicationStorageDirectory.resolvePath( "app-storage:/" + "medias/songs/empty.mp3");
			else
				_mp3Destination = File.applicationStorageDirectory.resolvePath( "medias/songs/empty.mp3");
			
			Debug.log("---> " + _mp3Empty.nativePath, 0xFF1122);	
			Debug.log("---> " + _mp3Destination.nativePath);	
				
			_mp3Empty.copyTo( _mp3Destination, true);
			
			
			if ( Capabilities.os.search("Mac") < 0 ) 
				_picDestination = File.applicationStorageDirectory.resolvePath( "app-storage:/" + "medias/thumbs/empty.jpg");
			else
				_picDestination = File.applicationStorageDirectory.resolvePath( "medias/thumbs/empty.jpg");
			
			Debug.log("---> " + _picEmpty.nativePath, 0xFF1122);	
			Debug.log("---> " + _picDestination.nativePath);	
				
			_picEmpty.copyTo( _picDestination, true);
			
			
			var allTracks:XML = DatasManager.getTracksXML();
			for each( var node : XML in allTracks.children())
			{
				
				/*
				 * MP3
				 */ 
				
				
				var _mp3Name 	: String = String(node.@file).split("medias/songs/")[1];				
				var _mp3Url		: String = SaveManager.OLD_URL_PATH_MP3 +"/"+ _mp3Name;
				var _mp3 		: File 	= new File(_mp3Url);
				
				if ( _mp3.exists && _mp3Name != "empty.mp3" )
				{
					if ( Capabilities.os.search("Mac") < 0 ) 
						_mp3Destination = File.applicationStorageDirectory.resolvePath( "app-storage:/" + "medias/songs/"+_mp3Name);
					else
						_mp3Destination = File.applicationStorageDirectory.resolvePath( "medias/songs/" + _mp3Name);
						
					try
					{	
						_mp3.copyTo( _mp3Destination, true);
					}
					catch (error:Error)
					{
						Debug.log("3: Error de copie de fichier: "+_mp3.name);
					}
				}
				
				
				/*
				 * JPG
				 */ 
				
				var _picName	: String = String(node.@pad_thumb).split("medias/thumbs/")[1];				
				var _picUrl		: String = SaveManager.OLD_URL_PATH_THUMB +"/"+ _picName;
				var _pic 		: File 	= new File(_picUrl);
				
				if ( _pic.exists && _picName != "empty.jpg" )
				{
					
					if ( Capabilities.os.search("Mac") < 0) 
						_picDestination = File.applicationStorageDirectory.resolvePath( "app-storage:/" + "medias/thumbs/" + _picName);
					else
						_picDestination = File.applicationStorageDirectory.resolvePath( "medias/thumbs/" + _picName);
						
					
					try
					{
						_pic.copyTo( _picDestination, true);
					}
					catch (error:Error)
					{
						Debug.log("3: Error de copie de fichier: "+_pic.name);
					}
				}
				
			}
			
			CONFIG::debug {
				trace("0:- urlCheckerManager ->" + (getTimer() - t1) + "ms");
			}
			
		}
		
	}

}